<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br />
    <el-card>
      <!-- 添加按钮  -->
      <el-button type="primary" @click="addRoleDialogVisible = true"
        >添加角色</el-button
      >

      <!-- 角色列表区域 row行 col列-->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['bdbottom',i1===0?'bdtop':'','rowcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightByID(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 row能还有row就是嵌套了 子行在父行同一行里面 这时候子row又有24个单位长 -->
                <el-row :class="[i2 === 0?'':'bdtop','rowcenter']" 
                v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightByID(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" closable @close="removeRightByID(scope.row,item3.id)" v-for="(item3,i3) in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>

                </el-row>
              </el-col>
            </el-row>
            
            
          </template>
        </el-table-column>

        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button size="mini" @click="showEditRoleDialog(scope.row)" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" @click="deleteRole(scope.row.id)" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button size="mini" type="warning" icon="el-icon-setting"
            @click="showSetRightDialog(scope.row)"

              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        @close="addRoleDialogClosed"
      >
        <el-form
          :model="addRoleForm"
          :rules="addRoleFormRules"
          ref="addRoleFormRef"
          label-width="80px"
        >
          <!-- 角色名称 -->
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <!-- 角色描述 -->
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogClosed">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑角色话框 -->
      <el-dialog
        title="修改角色信息"
        :visible.sync="editRoleDialogVisible"
        @close="editRoleDialogClosed"
      >
        <el-form
          :model="editRoleForm"
          :rules="addRoleFormRules"
          ref="editRoleFormRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogClosed">取 消</el-button>
          <el-button type="primary" @click="editRoleInfo"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      @close="setRightDialogClosed"
      width="50%">
      <el-tree :data="rightsList"
      :props="treeProps" 
      show-checkbox node-key="id" 
      default-expand-all 
      :default-checked-keys="defKeys"
      ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    

  </div>
</template>

<script>
export default {
  data() {
    return {
      rolelist: [],
      addRoleForm: {
        roleName: "",
        roleDesc: "",
      },
      editRoleForm: {
        roleName: "",
        roleDesc: "",
      },
      // 所有角色列表数据
      roleList:[],
      //所有权限的数据
      rightsList:[],
      //默认选中的节点ID值数组
      defKeys:[],
      //当前即将分配权限的角色id
      roleId:'',
      // 树形控件的属性绑定对象
      treeProps:{
        label:'authName',
        children:'children'

      },
      addRoleDialogVisible: false,
      editRoleDialogVisible:false,
      setRightDialogVisible:false,
      addRoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
      },
      
    };
  },
  methods: {
    //获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolelist = res.data;
    },
    //关闭对话框操作
    addRoleDialogClosed() {
      this.addRoleDialogVisible = false;
      this.$refs.addRoleFormRef.resetFields();
    },
    editRoleDialogClosed() {
      this.editRoleDialogVisible = false
      this.$refs.editRoleFormRef.resetFields()
    },
    // 展开编辑对话框
    showEditRoleDialog(row){
      this.editRoleDialogVisible = true
      this.editRoleForm = { ...row }
    },
    // 删除操作
    async deleteRole(id){
      const confirmResult =await this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirmResult !== 'confirm'){
          return this.$message.info('已取消删除')
        }
        const {data: res} = await this.$http.delete('roles/' + id)
        if(res.meta.status !== 200){
          return this.$message.error('删除用户失败')
        }
        this.$message.success('删除用户成功')
        this.getRolesList()
    },
    // 提交添加用户的数据
    addRole() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addRoleForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.addRoleDialogClosed();
        this.getRolesList();
      });
    },
    //提交编辑用户的信息
    editRoleInfo(){
      this.$refs.editRoleFormRef.validate(async (valid) =>{
        if(!valid) return;
        const{data:res}=await this.$http.put('roles/'+this.editRoleForm.id,{
          roleName:this.editRoleForm.roleName,
          roleDesc:this.editRoleForm.roleDesc,
        })
        if(res.meta.status !== 200){
          return this.$message.error('更新用户信息失败')
        }
        this.editRoleDialogVisible= false
        this.getRolesList()
        this.$message.success('更新用户信息成功')

      })
    },
    //展开分配权限对话框
    //获取所有权限数据
    async showSetRightDialog(role){
      this.roleId = role.id
      const {data:res} = await this.$http.get('rights/tree')
      if(res.meta.status != 200){
        return this.$message.error('获取权限失败')
      }
      this.rightsList = res.data

      // 递归获取三级节点id
      this.getLeafKeys(role,this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归形式获取角色下的三级权限id 并保存到defKeys中
    getLeafKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item => 
        this.getLeafKeys(item,arr))
    },
    // 监听分配权限对话框的关闭事件 不然获取的数据会一直堆积 所以得重新清空数组赋值
    setRightDialogClosed(){
      this.defKeys = []
    },
    // 点击确定为角色分配权限 
    async allotRights(){
      // 把两个数组合并成一个新数组
      const keys = [
        ...this.$refs.treeRef.
        getCheckedKeys(),
        ...this.$refs.treeRef.
        getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')

      const{data :res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})

      if(res.meta.status !== 200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 根据ID删除权限
    async removeRightByID(role,rightId){
      const confirmResult = await this.$confirm(
        "此操作将永久删除角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      this.$message.success("删除参数成功");
      // 因为一调用这个函数就会发生页面的完整渲染 所有不建议 直接赋值就行了
      // this.getRolesList();
      role.children = res.data
    }

  },
  created() {
    this.getRolesList();
  },
};
</script>

<style scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.rowcenter{
  display: flex;
  align-items: center;
}
</style>